<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Hello World</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            gap: 30px;
        }

        h1 {
            color: white;
            font-size: 48px;
            text-align: center;
            margin-bottom: 20px;
        }

        .button-container {
            display: flex;
            gap: 20px;
            flex-wrap: wrap;
            justify-content: center;
        }

        button {
            padding: 15px 30px;
            font-size: 16px;
            font-weight: 600;
            color: white;
            background: rgba(255, 255, 255, 0.2);
            border: 2px solid white;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s;
            backdrop-filter: blur(10px);
        }

        button:hover {
            background: rgba(255, 255, 255, 0.3);
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        }

        button:active {
            transform: translateY(0);
        }

        /* 消息提示动画 */
        @keyframes slideIn {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }
        
        @keyframes slideOut {
            from {
                transform: translateX(0);
                opacity: 1;
            }
            to {
                transform: translateX(100%);
                opacity: 0;
            }
        }
        
        /* 打印样式 */
        @media print {
            body {
                background: white !important;
                color: black !important;
        }
            .button-container {
                display: none !important;
            }
            h1 {
                color: black !important;
        }
        }
    </style>
</head>
<body>
    <h1>Hello World</h1>
    <div class="button-container">
        <button onclick="createSubWindow()">创建常规子窗</button>
        <button onclick="createFloatWindow()">创建悬浮窗</button>
        <button onclick="printPage()">🖨️ 打印</button>
        <button onclick="getBatteryInfo()">🔋 获取电量</button>
        <button onclick="showNotification()">🔔 显示通知</button>
        <button onclick="selectFile()">📁 选择文件</button>
        <button onclick="selectFiles()">📂 选择多个文件</button>
        <button onclick="selectFolder()">📁 选择文件夹</button>
        <button onclick="saveFile()">💾 保存文件</button>
        <!-- <button onclick="getWiFiInfo()">📶 获取WiFi信息</button> -->
        <button onclick="getIPAddresses()">🌐 获取IP地址</button>
        <button onclick="getChargingStatus()">🔌 检查充电状态</button>
        <button onclick="openCamera()">📷 打开摄像头</button>
        <button onclick="captureScreenshot()">📸 截图</button>
        <button onclick="startRecording()">🎤 开始录音</button>
        <button onclick="getCurrentLocation()">📍 获取地理位置</button>
        <button onclick="openBrowser()">🌐 打开浏览器</button>
        </div>
        
    <div id="battery-info" style="display: none; margin-top: 20px; padding: 20px; background: rgba(255, 255, 255, 0.1); border-radius: 10px; color: white; backdrop-filter: blur(10px);">
        <h2 style="margin-bottom: 15px;">电池信息</h2>
        <div id="battery-details"></div>
            </div>
        
    <div id="file-info" style="display: none; margin-top: 20px; padding: 20px; background: rgba(255, 255, 255, 0.1); border-radius: 10px; color: white; backdrop-filter: blur(10px); max-width: 800px; width: 90%;">
        <h2 style="margin-bottom: 15px;">文件信息</h2>
        <div id="file-details"></div>
        </div>
        
    <!-- <div id="wifi-info" style="display: none; margin-top: 20px; padding: 20px; background: rgba(255, 255, 255, 0.1); border-radius: 10px; color: white; backdrop-filter: blur(10px); max-width: 600px; width: 90%;">
        <h2 style="margin-bottom: 15px;">WiFi信息</h2>
        <div id="wifi-details"></div>
    </div> -->
        
    <div id="ip-info" style="display: none; margin-top: 20px; padding: 20px; background: rgba(255, 255, 255, 0.1); border-radius: 10px; color: white; backdrop-filter: blur(10px); max-width: 800px; width: 90%;">
        <h2 style="margin-bottom: 15px;">IP地址信息</h2>
        <div id="ip-details"></div>
    </div>
        
    <div id="charging-info" style="display: none; margin-top: 20px; padding: 20px; background: rgba(255, 255, 255, 0.1); border-radius: 10px; color: white; backdrop-filter: blur(10px); max-width: 600px; width: 90%;">
        <h2 style="margin-bottom: 15px;">充电状态</h2>
        <div id="charging-details"></div>
    </div>
        
    <div id="camera-container" style="display: none; margin-top: 20px; padding: 20px; background: rgba(255, 255, 255, 0.1); border-radius: 10px; color: white; backdrop-filter: blur(10px); max-width: 800px; width: 90%;">
        <h2 style="margin-bottom: 15px;">摄像头</h2>
        <div id="camera-controls" style="margin-bottom: 15px;">
            <button onclick="takePhoto()" style="margin-right: 10px;">📸 拍照</button>
            <button onclick="closeCamera()">❌ 关闭摄像头</button>
        </div>
        <video id="video-preview" autoplay playsinline style="width: 100%; max-width: 640px; border-radius: 8px; background: #000; display: none;"></video>
        <canvas id="photo-canvas" style="display: none;"></canvas>
        <div id="photo-preview" style="margin-top: 15px; display: none;">
            <h3 style="margin-bottom: 10px;">拍摄的照片：</h3>
            <img id="photo-image" style="max-width: 100%; border-radius: 8px; border: 2px solid rgba(255, 255, 255, 0.3);">
            <div style="margin-top: 10px;">
                <button onclick="savePhoto()" style="margin-right: 10px;">💾 保存照片</button>
                <button onclick="retakePhoto()">📷 重新拍摄</button>
            </div>
        </div>
        <div id="camera-error" style="display: none; color: #ff6b6b; margin-top: 15px;"></div>
    </div>
        
    <div id="location-info" style="display: none; margin-top: 20px; padding: 20px; background: rgba(255, 255, 255, 0.1); border-radius: 10px; color: white; backdrop-filter: blur(10px); max-width: 800px; width: 90%;">
        <h2 style="margin-bottom: 15px;">📍 地理位置信息</h2>
        <div id="location-details"></div>
        <div id="location-error" style="display: none; color: #ff6b6b; margin-top: 15px;"></div>
    </div>
    
    <!-- 浏览器URL输入对话框 -->
    <div id="browser-dialog" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.7); z-index: 10000; align-items: center; justify-content: center;">
        <div style="background: #2d2d2d; padding: 30px; border-radius: 10px; min-width: 400px; max-width: 600px; box-shadow: 0 4px 20px rgba(0,0,0,0.5);">
            <h2 style="margin-bottom: 20px; color: white;">🌐 打开浏览器</h2>
            <p style="margin-bottom: 15px; color: rgba(255, 255, 255, 0.8);">请输入要访问的网址：</p>
            <input type="text" id="browser-url-input" style="width: 100%; padding: 12px; background: #1a1a1a; border: 1px solid #404040; border-radius: 5px; color: white; font-size: 14px; margin-bottom: 20px; outline: none;" placeholder="https://www.example.com">
            <div style="display: flex; gap: 10px; justify-content: flex-end;">
                <button id="browser-dialog-cancel" style="padding: 10px 20px; background: #404040; color: white; border: none; border-radius: 5px; cursor: pointer; font-size: 14px;">取消</button>
                <button id="browser-dialog-ok" style="padding: 10px 20px; background: #51cf66; color: white; border: none; border-radius: 5px; cursor: pointer; font-size: 14px; font-weight: bold;">打开</button>
            </div>
        </div>
    </div>
        
    <div id="recording-container" style="display: none; margin-top: 20px; padding: 20px; background: rgba(255, 255, 255, 0.1); border-radius: 10px; color: white; backdrop-filter: blur(10px); max-width: 800px; width: 90%;">
        <h2 style="margin-bottom: 15px;">录音</h2>
        <div id="recording-controls" style="margin-bottom: 15px;">
            <button id="start-recording-btn" onclick="startRecording()" style="margin-right: 10px;">🎤 开始录音</button>
            <button id="stop-recording-btn" onclick="stopRecording()" style="margin-right: 10px; display: none;">⏹️ 停止录音</button>
            <button id="play-recording-btn" onclick="playRecording()" style="margin-right: 10px; display: none;">▶️ 播放录音</button>
            <button id="pause-recording-btn" onclick="pauseRecording()" style="margin-right: 10px; display: none;">⏸️ 暂停播放</button>
            <button id="save-recording-btn" onclick="saveRecording()" style="margin-right: 10px; display: none;">💾 保存录音</button>
            <button onclick="closeRecording()">❌ 关闭录音</button>
        </div>
        <div id="recording-status" style="margin-bottom: 15px; padding: 10px; background: rgba(255, 255, 255, 0.05); border-radius: 5px;">
            <div id="recording-time" style="font-size: 18px; font-weight: bold; color: #ff6b6b;">00:00</div>
            <div id="recording-indicator" style="display: none; margin-top: 5px;">
                <span style="display: inline-block; width: 12px; height: 12px; background: #ff6b6b; border-radius: 50%; margin-right: 5px; animation: pulse 1s infinite;"></span>
                <span>正在录音...</span>
            </div>
        </div>
        <audio id="audio-player" controls style="width: 100%; display: none; margin-top: 15px;"></audio>
        <div id="recording-info" style="margin-top: 15px; padding: 10px; background: rgba(255, 255, 255, 0.05); border-radius: 5px; display: none;">
            <div><strong>录音时长:</strong> <span id="recording-duration">0 秒</span></div>
            <div style="margin-top: 5px;"><strong>文件大小:</strong> <span id="recording-size">0 KB</span></div>
        </div>
        <div id="recording-error" style="display: none; color: #ff6b6b; margin-top: 15px;"></div>
        <style>
            @keyframes pulse {
                0%, 100% { opacity: 1; }
                50% { opacity: 0.5; }
            }
        </style>
    </div>
        
    <div id="screenshot-container" style="display: none; margin-top: 20px; padding: 20px; background: rgba(255, 255, 255, 0.1); border-radius: 10px; color: white; backdrop-filter: blur(10px); max-width: 800px; width: 90%;">
        <h2 style="margin-bottom: 15px;">截图</h2>
        <div id="screenshot-controls" style="margin-bottom: 15px;">
            <button onclick="captureWindow()" style="margin-right: 10px;">🪟 截取窗口</button>
            <button onclick="captureScreen()" style="margin-right: 10px;">🖥️ 截取屏幕</button>
            <button onclick="captureRegion()" style="margin-right: 10px;">📐 区域选择</button>
            <button onclick="closeScreenshot()">❌ 关闭</button>
        </div>
        <div id="screenshot-preview" style="margin-top: 15px; display: none;">
            <h3 style="margin-bottom: 10px;">截图预览：</h3>
            <img id="screenshot-image" style="max-width: 100%; border-radius: 8px; border: 2px solid rgba(255, 255, 255, 0.3);">
            <div style="margin-top: 10px; color: rgba(255, 255, 255, 0.8);">
                <div id="screenshot-info"></div>
            </div>
            <div style="margin-top: 10px;">
                <button onclick="saveScreenshot()" style="margin-right: 10px;">💾 保存截图</button>
                <button onclick="retakeScreenshot()">📸 重新截图</button>
            </div>
        </div>
        <div id="screenshot-error" style="display: none; color: #ff6b6b; margin-top: 15px;"></div>
    </div>

    <script>
        function createSubWindow() {
            if (window.electronAPI && window.electronAPI.createSubWindow) {
                window.electronAPI.createSubWindow();
            } else {
                alert('创建子窗功能不可用');
            }
        }

        function createFloatWindow() {
            if (window.electronAPI && window.electronAPI.createFloatWindow) {
                window.electronAPI.createFloatWindow();
            } else {
                alert('创建悬浮窗功能不可用');
            }
        }

        function printPage() {
            console.log('点击打印按钮');
            // 先显示一个提示，确认按钮点击事件正常
            alert('准备打印...');
            
            try {
                // 方法1: 直接使用浏览器原生打印 API（在鸿蒙平台上更可靠）
                if (typeof window.print === 'function') {
                    console.log('调用 window.print()');
                    window.print();
                } else if (window.electronAPI && window.electronAPI.print) {
                    // 方法2: 使用 Electron IPC 打印
                    console.log('使用 Electron IPC 打印');
                    window.electronAPI.print();
                } else {
                    alert('打印功能不可用：window.print 和 electronAPI.print 都不可用');
                }
            } catch (error) {
                console.error('打印失败:', error);
                alert('打印功能出错: ' + error.message);
            }
        }

        // 获取电池信息
        async function getBatteryInfo() {
            console.log('点击获取电量按钮');
            const batteryInfoDiv = document.getElementById('battery-info');
            const batteryDetailsDiv = document.getElementById('battery-details');
            
            try {
                // 方法1: 优先使用 HTML5 Battery API（如果可用）
                if (navigator.getBattery) {
                    console.log('使用 HTML5 Battery API');
                    const battery = await navigator.getBattery();
                    const batteryInfo = {
                        level: Math.round(battery.level * 100),
                        charging: battery.charging,
                        chargingTime: battery.chargingTime,
                        dischargingTime: battery.dischargingTime
                    };
                    displayBatteryInfo(batteryInfo);
                    
                    // 监听电池状态变化
                    battery.addEventListener('chargingchange', () => {
                        updateBatteryInfo(battery);
                    });
                    battery.addEventListener('levelchange', () => {
                        updateBatteryInfo(battery);
                    });
                } else if (window.electronAPI && window.electronAPI.getBatteryLevel) {
                    // 方法2: 使用 Electron IPC 获取电池信息
                    console.log('使用 Electron IPC 获取电池信息');
                    const batteryInfo = await window.electronAPI.getBatteryLevel();
                    displayBatteryInfo(batteryInfo);
                    
                    // 监听电池状态变化
                    if (window.electronAPI.onBatteryStatusChange) {
                        window.electronAPI.onBatteryStatusChange((batteryInfo) => {
                            displayBatteryInfo(batteryInfo);
                        });
                    }
                } else {
                    alert('电池信息功能不可用');
                    return;
                }
            } catch (error) {
                console.error('获取电池信息失败:', error);
                batteryDetailsDiv.innerHTML = '<p style="color: #ff6b6b;">获取电池信息失败: ' + error.message + '</p>';
                batteryInfoDiv.style.display = 'block';
            }
        }

        function displayBatteryInfo(batteryInfo) {
            const batteryInfoDiv = document.getElementById('battery-info');
            const batteryDetailsDiv = document.getElementById('battery-details');
            
            let html = '';
            
            if (batteryInfo.level !== null && batteryInfo.level !== undefined) {
                const level = batteryInfo.level;
                const levelColor = level > 50 ? '#51cf66' : level > 20 ? '#ffd43b' : '#ff6b6b';
                
                html += `<div style="margin-bottom: 10px;">
                    <strong>电量:</strong> 
                    <span style="color: ${levelColor}; font-size: 24px; font-weight: bold;">${level}%</span>
                </div>`;
                
                // 电量条
                html += `<div style="width: 300px; height: 20px; background: rgba(255, 255, 255, 0.2); border-radius: 10px; overflow: hidden; margin: 10px 0;">
                    <div style="width: ${level}%; height: 100%; background: ${levelColor}; transition: width 0.3s;"></div>
                </div>`;
            } else {
                html += '<div style="margin-bottom: 10px;"><strong>电量:</strong> 无法获取</div>';
        }

            if (batteryInfo.charging !== null && batteryInfo.charging !== undefined) {
                html += `<div style="margin-bottom: 10px;">
                    <strong>充电状态:</strong> 
                    <span style="color: ${batteryInfo.charging ? '#51cf66' : '#ffd43b'};">
                        ${batteryInfo.charging ? '🔌 正在充电' : '🔋 使用电池'}
                    </span>
                </div>`;
            }
            
            if (batteryInfo.chargingTime !== null && batteryInfo.chargingTime !== undefined && batteryInfo.chargingTime !== Infinity) {
                const hours = Math.floor(batteryInfo.chargingTime / 3600);
                const minutes = Math.floor((batteryInfo.chargingTime % 3600) / 60);
                html += `<div style="margin-bottom: 10px;">
                    <strong>充满电时间:</strong> ${hours}小时${minutes}分钟
                </div>`;
            }
            
            if (batteryInfo.dischargingTime !== null && batteryInfo.dischargingTime !== undefined && batteryInfo.dischargingTime !== Infinity) {
                const hours = Math.floor(batteryInfo.dischargingTime / 3600);
                const minutes = Math.floor((batteryInfo.dischargingTime % 3600) / 60);
                html += `<div style="margin-bottom: 10px;">
                    <strong>预计使用时间:</strong> ${hours}小时${minutes}分钟
                </div>`;
            }
            
            if (batteryInfo.error) {
                html += `<div style="color: #ff6b6b; margin-top: 10px;">错误: ${batteryInfo.error}</div>`;
                    }
            
            batteryDetailsDiv.innerHTML = html;
            batteryInfoDiv.style.display = 'block';
        }

        function updateBatteryInfo(battery) {
            const batteryInfo = {
                level: Math.round(battery.level * 100),
                charging: battery.charging,
                chargingTime: battery.chargingTime,
                dischargingTime: battery.dischargingTime
            };
            displayBatteryInfo(batteryInfo);
        }

        // 显示通知
        async function showNotification() {
            console.log('点击显示通知按钮');
            
            try {
                // 方法1: 优先使用浏览器原生 Notification API
                if ('Notification' in window) {
                    // 请求权限
                    if (Notification.permission === 'default') {
                        const permission = await Notification.requestPermission();
                        if (permission !== 'granted') {
                            alert('通知权限被拒绝');
                            return;
                        }
                    }
                    
                    if (Notification.permission === 'granted') {
                        // 使用浏览器原生通知
                        const notification = new Notification('坚果通知', {
                            body: '这是来自坚果的通知',
                            icon: undefined, // 可以设置图标路径
                            badge: undefined,
                            tag: 'electron-notification',
                            requireInteraction: false,
                            silent: false
                        });
                        
                        notification.onclick = () => {
                            console.log('通知被点击');
                            window.focus();
                        };
                        
                        notification.onshow = () => {
                            console.log('通知已显示');
                        };
                        
                        notification.onclose = () => {
                            console.log('通知已关闭');
                        };
                        
                        notification.onerror = (error) => {
                            console.error('通知错误:', error);
                        };
                        
                        return;
                    }
                }
                
                // 方法2: 使用 Electron IPC 显示通知
                if (window.electronAPI && window.electronAPI.showNotification) {
                    console.log('使用 Electron IPC 显示通知');
                    
                    // 检测平台，使用不同的选项
                    const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0;
                    const notificationOptions = {
                        title: '坚果通知',
                        body: '这是来自坚果的通知',
                        message: '这是来自坚果的通知',
                        notificationId: Date.now(),
                        silent: false,
                        onClick: true
                    };
                    
                    // macOS 特殊选项
                    if (isMac) {
                        notificationOptions.subtitle = '坚果派';
                        notificationOptions.sound = 'default';
                    } else {
                        notificationOptions.urgency = 'normal';
                    }
                    
                    console.log('通知选项:', notificationOptions);
                    
                    const result = await window.electronAPI.showNotification(notificationOptions);
                    
                    if (result.success) {
                        console.log('通知显示成功，ID:', result.notificationId);
                        alert('通知已发送！ID: ' + result.notificationId);
                    
                        // 监听通知点击事件
                        if (window.electronAPI.onNotificationClick) {
                            window.electronAPI.onNotificationClick((notificationId) => {
                                console.log('通知被点击:', notificationId);
                                alert('通知 ID ' + notificationId + ' 被点击了！');
                            });
                    }
                    } else {
                        console.error('显示通知失败:', result.error);
                        alert('显示通知失败: ' + result.error + '\n\n请检查：\n1. 系统通知权限是否已授予\n2. 应用是否在 Dock 中（macOS）\n3. 系统通知设置是否允许此应用');
                    }
                } else {
                    alert('通知功能不可用');
                }
            } catch (error) {
                console.error('显示通知失败:', error);
                alert('显示通知出错: ' + error.message);
            }
        }
        
        // 选择单个文件
        async function selectFile() {
            console.log('点击选择文件按钮');
            
            try {
                if (window.electronAPI && window.electronAPI.selectFile) {
                    const result = await window.electronAPI.selectFile({
                        title: '选择文件',
                        filters: [
                            { name: '图片', extensions: ['jpg', 'png', 'gif', 'bmp', 'webp'] },
                            { name: '文档', extensions: ['txt', 'doc', 'docx', 'pdf'] },
                            { name: '所有文件', extensions: ['*'] }
                        ]
                    });

                    if (!result.canceled && result.filePaths && result.filePaths.length > 0) {
                        displayFileInfo(result.filePaths);
                        
                        // 如果是文本文件，尝试读取内容
                        const filePath = result.filePaths[0];
                        if (filePath.match(/\.(txt|json|js|html|css|md)$/i)) {
                            const readResult = await window.electronAPI.readFile(filePath);
                            if (readResult.success) {
                                displayFileContent(filePath, readResult.content, readResult.size);
                            }
                        }
                    } else {
                        console.log('用户取消了文件选择');
                    }
                } else {
                    alert('文件选择功能不可用');
                }
            } catch (error) {
                console.error('选择文件失败:', error);
                alert('选择文件出错: ' + error.message);
            }
        }

        // 选择多个文件
        async function selectFiles() {
            console.log('点击选择多个文件按钮');
            
            try {
                if (window.electronAPI && window.electronAPI.selectFiles) {
                    const result = await window.electronAPI.selectFiles({
                        title: '选择多个文件',
                        filters: [
                            { name: '图片', extensions: ['jpg', 'png', 'gif', 'bmp', 'webp'] },
                            { name: '文档', extensions: ['txt', 'doc', 'docx', 'pdf'] },
                            { name: '所有文件', extensions: ['*'] }
                        ]
                    });

                    if (!result.canceled && result.filePaths && result.filePaths.length > 0) {
                        displayFileInfo(result.filePaths);
                    } else {
                        console.log('用户取消了文件选择');
                    }
                } else {
                    alert('文件选择功能不可用');
                }
            } catch (error) {
                console.error('选择文件失败:', error);
                alert('选择文件出错: ' + error.message);
            }
        }

        // 选择文件夹
        async function selectFolder() {
            console.log('点击选择文件夹按钮');
            
            try {
                if (window.electronAPI && window.electronAPI.selectFolder) {
                    const result = await window.electronAPI.selectFolder({
                        title: '选择文件夹'
                    });

                    if (!result.canceled && result.filePaths && result.filePaths.length > 0) {
                        displayFileInfo(result.filePaths);
                    } else {
                        console.log('用户取消了文件夹选择');
                    }
                } else {
                    alert('文件夹选择功能不可用');
                }
            } catch (error) {
                console.error('选择文件夹失败:', error);
                alert('选择文件夹出错: ' + error.message);
            }
        }

        // 保存文件
        async function saveFile() {
            console.log('点击保存文件按钮');
            
            try {
                if (window.electronAPI && window.electronAPI.saveFile) {
                    // 示例：保存一些文本内容
                    const content = `这是保存的文件内容
创建时间: ${new Date().toLocaleString()}
平台: ${navigator.platform}
用户代理: ${navigator.userAgent}`;

                    const result = await window.electronAPI.saveFile({
                        title: '保存文件',
                        defaultPath: 'example.txt',
                        filters: [
                            { name: '文本文件', extensions: ['txt'] },
                            { name: '所有文件', extensions: ['*'] }
                        ],
                        content: content,
                        encoding: 'utf8'
                    });

                    if (!result.canceled && result.filePath) {
                        if (result.saved) {
                            alert(`文件已保存到:\n${result.filePath}`);
                            displayFileInfo([result.filePath]);
                        } else {
                            alert(`请将内容保存到:\n${result.filePath}`);
                        }
                    } else {
                        console.log('用户取消了保存文件');
                    }
                } else {
                    alert('保存文件功能不可用');
                }
            } catch (error) {
                console.error('保存文件失败:', error);
                alert('保存文件出错: ' + error.message);
            }
        }

        // 显示文件信息
        function displayFileInfo(filePaths) {
            const fileInfoDiv = document.getElementById('file-info');
            const fileDetailsDiv = document.getElementById('file-details');
            
            let html = '';
            
            if (filePaths.length === 1) {
                const filePath = filePaths[0];
                const fileName = filePath.split(/[/\\]/).pop();
                html += `<div style="margin-bottom: 15px;">
                    <strong>文件名:</strong> <span style="color: #51cf66;">${fileName}</span>
                </div>`;
                html += `<div style="margin-bottom: 15px;">
                    <strong>完整路径:</strong> <span style="word-break: break-all; font-size: 12px;">${filePath}</span>
                </div>`;
            } else {
                html += `<div style="margin-bottom: 15px;">
                    <strong>已选择 ${filePaths.length} 个文件/文件夹:</strong>
                </div>`;
                html += '<div style="max-height: 300px; overflow-y: auto;">';
                filePaths.forEach((filePath, index) => {
                    const fileName = filePath.split(/[/\\]/).pop();
                    html += `<div style="margin-bottom: 10px; padding: 8px; background: rgba(255, 255, 255, 0.05); border-radius: 5px;">
                        <strong>${index + 1}.</strong> ${fileName}<br>
                        <span style="font-size: 11px; color: rgba(255, 255, 255, 0.7); word-break: break-all;">${filePath}</span>
                    </div>`;
                });
                html += '</div>';
            }
            
            fileDetailsDiv.innerHTML = html;
            fileInfoDiv.style.display = 'block';
        }

        // 显示文件内容
        function displayFileContent(filePath, content, size) {
            const fileDetailsDiv = document.getElementById('file-details');
            const fileName = filePath.split(/[/\\]/).pop();
            
            let html = fileDetailsDiv.innerHTML;
            html += `<div style="margin-top: 15px; padding-top: 15px; border-top: 1px solid rgba(255, 255, 255, 0.2);">
                <strong>文件大小:</strong> ${formatFileSize(size)}<br>
                <strong>文件内容预览:</strong>
                <div style="margin-top: 10px; padding: 10px; background: rgba(0, 0, 0, 0.2); border-radius: 5px; max-height: 200px; overflow-y: auto; font-family: monospace; font-size: 12px; white-space: pre-wrap; word-break: break-all;">
${content.length > 1000 ? content.substring(0, 1000) + '...\n\n(内容过长，仅显示前1000个字符)' : content}
        </div>
            </div>`;
            
            fileDetailsDiv.innerHTML = html;
        }

        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 B';
            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
        }
        
        // 获取WiFi信息（已注释）
        /*
        async function getWiFiInfo() {
            console.log('点击获取WiFi信息按钮');
            const wifiInfoDiv = document.getElementById('wifi-info');
            const wifiDetailsDiv = document.getElementById('wifi-details');
            
            try {
                if (window.electronAPI && window.electronAPI.getWiFiInfo) {
                    console.log('使用 Electron IPC 获取WiFi信息');
                    const wifiInfo = await window.electronAPI.getWiFiInfo();
                    displayWiFiInfo(wifiInfo);
                } else {
                    alert('WiFi信息功能不可用');
                }
            } catch (error) {
                console.error('获取WiFi信息失败:', error);
                wifiDetailsDiv.innerHTML = '<p style="color: #ff6b6b;">获取WiFi信息失败: ' + error.message + '</p>';
                wifiInfoDiv.style.display = 'block';
            }
        }

        function displayWiFiInfo(wifiInfo) {
            const wifiInfoDiv = document.getElementById('wifi-info');
            const wifiDetailsDiv = document.getElementById('wifi-details');
            
            let html = '';
            
            if (wifiInfo.error) {
                html += `<div style="color: #ff6b6b; margin-bottom: 10px;">
                    <strong>错误:</strong> ${wifiInfo.error}
                </div>`;
            }
            
            if (wifiInfo.platform) {
                html += `<div style="margin-bottom: 10px;">
                    <strong>平台:</strong> <span style="color: #51cf66;">${wifiInfo.platform}</span>
                </div>`;
            }
            
            if (wifiInfo.ssid) {
                html += `<div style="margin-bottom: 10px;">
                    <strong>网络名称 (SSID):</strong> 
                    <span style="color: #51cf66; font-size: 18px; font-weight: bold;">${wifiInfo.ssid}</span>
                </div>`;
            } else {
                html += `<div style="margin-bottom: 10px;">
                    <strong>网络名称 (SSID):</strong> 
                    <span style="color: #ffd43b;">未连接或无法获取</span>
                </div>`;
            }
            
            if (wifiInfo.bssid) {
                html += `<div style="margin-bottom: 10px;">
                    <strong>MAC地址 (BSSID):</strong> 
                    <span style="font-family: monospace; color: #51cf66;">${wifiInfo.bssid}</span>
                </div>`;
            }
            
            if (wifiInfo.signal !== null && wifiInfo.signal !== undefined) {
                let signalColor = '#51cf66'; // 绿色
                let signalText = '强';
                if (wifiInfo.signal < -70) {
                    signalColor = '#ff6b6b'; // 红色
                    signalText = '弱';
                } else if (wifiInfo.signal < -60) {
                    signalColor = '#ffd43b'; // 黄色
                    signalText = '中等';
                }
                
                html += `<div style="margin-bottom: 10px;">
                    <strong>信号强度:</strong> 
                    <span style="color: ${signalColor}; font-weight: bold;">${wifiInfo.signal}% (${signalText})</span>
                </div>`;
                
                // 信号强度条
                const signalPercent = Math.max(0, Math.min(100, wifiInfo.signal + 100)); // 将-100到0映射到0到100
                html += `<div style="width: 300px; height: 20px; background: rgba(255, 255, 255, 0.2); border-radius: 10px; overflow: hidden; margin: 10px 0;">
                    <div style="width: ${signalPercent}%; height: 100%; background: ${signalColor}; transition: width 0.3s;"></div>
                </div>`;
            }
            
            if (wifiInfo.channel !== null && wifiInfo.channel !== undefined) {
                html += `<div style="margin-bottom: 10px;">
                    <strong>频道:</strong> 
                    <span style="color: #51cf66;">${wifiInfo.channel}</span>
                </div>`;
            }
            
            if (wifiInfo.radioType) {
                html += `<div style="margin-bottom: 10px;">
                    <strong>无线类型:</strong> 
                    <span style="color: #51cf66;">${wifiInfo.radioType}</span>
                </div>`;
            }
            
            if (wifiInfo.state) {
                html += `<div style="margin-bottom: 10px;">
                    <strong>连接状态:</strong> 
                    <span style="color: ${wifiInfo.state.toLowerCase().includes('connected') ? '#51cf66' : '#ffd43b'};">
                        ${wifiInfo.state}
                    </span>
                </div>`;
            }
            
            wifiDetailsDiv.innerHTML = html;
            wifiInfoDiv.style.display = 'block';
        }
        */
        
        // 获取IP地址
        async function getIPAddresses() {
            console.log('点击获取IP地址按钮');
            const ipInfoDiv = document.getElementById('ip-info');
            const ipDetailsDiv = document.getElementById('ip-details');
            
            try {
                if (window.electronAPI && window.electronAPI.getIPAddresses) {
                    console.log('使用 Electron IPC 获取IP地址');
                    const ipInfo = await window.electronAPI.getIPAddresses();
                    displayIPInfo(ipInfo);
                } else {
                    alert('IP地址功能不可用');
                }
            } catch (error) {
                console.error('获取IP地址失败:', error);
                ipDetailsDiv.innerHTML = '<p style="color: #ff6b6b;">获取IP地址失败: ' + error.message + '</p>';
                ipInfoDiv.style.display = 'block';
            }
        }

        function displayIPInfo(ipInfo) {
            const ipInfoDiv = document.getElementById('ip-info');
            const ipDetailsDiv = document.getElementById('ip-details');
            
            let html = '';
            
            if (ipInfo.error) {
                html += `<div style="color: #ff6b6b; margin-bottom: 10px;">
                    <strong>错误:</strong> ${ipInfo.error}
                </div>`;
            }
            
            if (ipInfo.platform) {
                html += `<div style="margin-bottom: 15px;">
                    <strong>平台:</strong> <span style="color: #51cf66;">${ipInfo.platform}</span>
                </div>`;
            }
            
            if (ipInfo.hostname) {
                html += `<div style="margin-bottom: 15px;">
                    <strong>主机名:</strong> 
                    <span style="color: #51cf66; font-size: 18px; font-weight: bold;">${ipInfo.hostname}</span>
                </div>`;
            }
            
            if (ipInfo.publicIP) {
                html += `<div style="margin-bottom: 15px; padding: 10px; background: rgba(81, 207, 102, 0.2); border-radius: 5px; border-left: 3px solid #51cf66;">
                    <strong>公网IP:</strong> 
                    <span style="color: #51cf66; font-size: 18px; font-weight: bold; font-family: monospace;">${ipInfo.publicIP}</span>
                </div>`;
            } else {
                html += `<div style="margin-bottom: 15px; padding: 10px; background: rgba(255, 212, 59, 0.2); border-radius: 5px;">
                    <strong>公网IP:</strong> 
                    <span style="color: #ffd43b;">无法获取（可能需要网络连接）</span>
                </div>`;
            }
            
            if (ipInfo.interfaces && ipInfo.interfaces.length > 0) {
                html += `<div style="margin-top: 20px;">
                    <strong style="font-size: 16px;">网络接口 (${ipInfo.interfaces.length}个):</strong>
                </div>`;
                
                html += '<div style="margin-top: 10px;">';
                ipInfo.interfaces.forEach((iface, index) => {
                    html += `<div style="margin-bottom: 15px; padding: 15px; background: rgba(255, 255, 255, 0.05); border-radius: 8px; border-left: 3px solid #51cf66;">
                        <div style="margin-bottom: 8px;">
                            <strong>接口 ${index + 1}:</strong> 
                            <span style="color: #51cf66; font-weight: bold;">${iface.interface}</span>
            </div>
                        <div style="margin-bottom: 5px;">
                            <strong>IP地址:</strong> 
                            <span style="color: #51cf66; font-size: 16px; font-weight: bold; font-family: monospace;">${iface.address}</span>
        </div>
                        <div style="margin-bottom: 5px;">
                            <strong>子网掩码:</strong> 
                            <span style="color: #ffd43b; font-family: monospace;">${iface.netmask}</span>
                        </div>`;
                    
                    if (iface.mac) {
                        html += `<div>
                            <strong>MAC地址:</strong> 
                            <span style="color: #ffd43b; font-family: monospace;">${iface.mac}</span>
                        </div>`;
                    }
                    
                    html += `</div>`;
                });
                html += '</div>';
            } else {
                html += `<div style="margin-top: 15px; padding: 10px; background: rgba(255, 107, 107, 0.2); border-radius: 5px;">
                    <strong>网络接口:</strong> 
                    <span style="color: #ff6b6b;">未找到可用的网络接口</span>
                </div>`;
            }
            
            ipDetailsDiv.innerHTML = html;
            ipInfoDiv.style.display = 'block';
        }
        
        // 获取充电状态
        async function getChargingStatus() {
            console.log('点击检查充电状态按钮');
            const chargingInfoDiv = document.getElementById('charging-info');
            const chargingDetailsDiv = document.getElementById('charging-details');
            
            try {
                if (window.electronAPI && window.electronAPI.getChargingStatus) {
                    console.log('使用 Electron IPC 获取充电状态');
                    const chargingStatus = await window.electronAPI.getChargingStatus();
                    displayChargingStatus(chargingStatus);
                    
                    // 监听充电状态变化
                    if (window.electronAPI.onChargingStatusChange) {
                        window.electronAPI.onChargingStatusChange((status) => {
                            console.log('充电状态变化:', status);
                            displayChargingStatus({ ...chargingStatus, isCharging: status.isCharging });
                        });
                    }
                } else {
                    alert('充电状态功能不可用');
                }
            } catch (error) {
                console.error('获取充电状态失败:', error);
                chargingDetailsDiv.innerHTML = '<p style="color: #ff6b6b;">获取充电状态失败: ' + error.message + '</p>';
                chargingInfoDiv.style.display = 'block';
            }
        }

        function displayChargingStatus(status) {
            const chargingInfoDiv = document.getElementById('charging-info');
            const chargingDetailsDiv = document.getElementById('charging-details');
            
            let html = '';
            
            if (status.error) {
                html += `<div style="color: #ff6b6b; margin-bottom: 10px;">
                    <strong>错误:</strong> ${status.error}
                </div>`;
            }
            
            if (status.platform) {
                html += `<div style="margin-bottom: 15px;">
                    <strong>平台:</strong> <span style="color: #51cf66;">${status.platform}</span>
                </div>`;
            }
            
            if (status.method) {
                html += `<div style="margin-bottom: 10px;">
                    <strong>检测方法:</strong> <span style="color: #ffd43b;">${status.method}</span>
                </div>`;
            }
            
            if (status.isCharging !== null && status.isCharging !== undefined) {
                const statusColor = status.isCharging ? '#51cf66' : '#ffd43b';
                const statusText = status.isCharging ? '🔌 正在充电' : '🔋 使用电池';
                const statusIcon = status.isCharging ? '🔌' : '🔋';
                
                html += `<div style="margin-top: 20px; padding: 20px; background: ${status.isCharging ? 'rgba(81, 207, 102, 0.2)' : 'rgba(255, 212, 59, 0.2)'}; border-radius: 10px; border-left: 4px solid ${statusColor};">
                    <div style="font-size: 48px; text-align: center; margin-bottom: 15px;">
                        ${statusIcon}
        </div>
                    <div style="text-align: center; font-size: 24px; font-weight: bold; color: ${statusColor}; margin-bottom: 10px;">
                        ${statusText}
    </div>
                    <div style="text-align: center; color: rgba(255, 255, 255, 0.8);">
                        ${status.isCharging ? '设备已连接到电源适配器' : '设备正在使用电池供电'}
                    </div>
                </div>`;
            } else {
                html += `<div style="margin-top: 20px; padding: 20px; background: rgba(255, 107, 107, 0.2); border-radius: 10px; border-left: 4px solid #ff6b6b;">
                    <div style="font-size: 48px; text-align: center; margin-bottom: 15px;">
                        ❓
                    </div>
                    <div style="text-align: center; font-size: 24px; font-weight: bold; color: #ff6b6b; margin-bottom: 10px;">
                        无法确定充电状态
                    </div>
                    <div style="text-align: center; color: rgba(255, 255, 255, 0.8);">
                        可能原因：设备没有电池、系统不支持或检测方法失败
                            </div>
                </div>`;
            }
            
            if (status.source) {
                html += `<div style="margin-top: 15px; padding: 10px; background: rgba(255, 255, 255, 0.05); border-radius: 5px;">
                    <strong>数据来源:</strong> <span style="color: #ffd43b; font-family: monospace;">${status.source}</span>
                </div>`;
            }
            
            chargingDetailsDiv.innerHTML = html;
            chargingInfoDiv.style.display = 'block';
        }
        
        // 摄像头相关变量
        let currentStream = null;
        let currentPhotoData = null;
        
        // 打开摄像头
        async function openCamera() {
            console.log('点击打开摄像头按钮');
            const cameraContainer = document.getElementById('camera-container');
            const videoPreview = document.getElementById('video-preview');
            const cameraError = document.getElementById('camera-error');
            const photoPreview = document.getElementById('photo-preview');
            
            // 隐藏之前的错误和照片预览
            cameraError.style.display = 'none';
            photoPreview.style.display = 'none';
            cameraContainer.style.display = 'block';
            
            try {
                // 检查浏览器是否支持getUserMedia
                if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
                    throw new Error('您的浏览器不支持摄像头访问功能');
                }
                
                console.log('开始请求摄像头权限...');
                
                // 创建一个带超时的 getUserMedia Promise
                const createGetUserMediaWithTimeout = (constraints, timeout = 10000) => {
                    return Promise.race([
                        navigator.mediaDevices.getUserMedia(constraints),
                        new Promise((_, reject) => {
                            setTimeout(() => {
                                reject(new Error('Timeout starting video source'));
                            }, timeout);
                        })
                    ]);
                };
                
                // 请求摄像头权限并获取视频流
                // 优先使用高质量配置，如果失败则降级
                const constraints = {
                    video: {
                        width: { ideal: 1280, min: 640 },
                        height: { ideal: 720, min: 480 },
                        facingMode: 'user', // 优先使用前置摄像头
                        aspectRatio: { ideal: 16/9 }
                    }
                };
                
                try {
                    // 使用带超时的 getUserMedia（10秒超时）
                    currentStream = await createGetUserMediaWithTimeout(constraints, 10000);
                    console.log('摄像头已获取，视频轨道数:', currentStream.getVideoTracks().length);
                    
                    // 检查视频轨道
                    const videoTracks = currentStream.getVideoTracks();
                    if (videoTracks.length === 0) {
                        throw new Error('未获取到视频轨道');
                    }
                    
                    // 显示视频轨道信息
                    const track = videoTracks[0];
                    const settings = track.getSettings();
                    console.log('视频轨道信息:', {
                        label: track.label,
                        enabled: track.enabled,
                        muted: track.muted,
                        readyState: track.readyState,
                        settings: settings
                    });
                    
                    // 显示视频流
                    videoPreview.srcObject = currentStream;
                    videoPreview.style.display = 'block';
                    
                    // 等待视频加载
                    videoPreview.onloadedmetadata = () => {
                        console.log('视频元数据已加载:', {
                            videoWidth: videoPreview.videoWidth,
                            videoHeight: videoPreview.videoHeight,
                            readyState: videoPreview.readyState
                        });
                    };
                    
                    // 监听视频播放错误
                    videoPreview.onerror = (error) => {
                        console.error('视频播放错误:', error);
                        cameraError.style.display = 'block';
                        cameraError.textContent = '视频流播放失败，请重试';
                    };
                    
                    console.log('摄像头已打开');
                } catch (getUserMediaError) {
                    console.error('getUserMedia 错误详情:', getUserMediaError);
                    const errorName = getUserMediaError.name;
                    const errorMessage = getUserMediaError.message;
                    
                    if (errorName === 'NotAllowedError' || errorName === 'PermissionDeniedError') {
                        throw new Error('摄像头权限被拒绝，请在系统设置中允许应用访问摄像头');
                    } else if (errorName === 'NotFoundError' || errorName === 'DevicesNotFoundError') {
                        throw new Error('未找到可用的摄像头设备');
                    } else if (errorName === 'NotReadableError' || errorName === 'TrackStartError') {
                        throw new Error('摄像头被其他应用占用，请关闭其他使用摄像头的应用后重试');
                    } else if (errorName === 'OverconstrainedError' || errorName === 'ConstraintNotSatisfiedError') {
                        // 尝试使用更简单的约束
                        console.log('约束不满足，尝试使用简单约束...');
                        const simpleConstraints = { 
                            video: {
                                facingMode: 'user'
                            }
                        };
                        try {
                            currentStream = await createGetUserMediaWithTimeout(simpleConstraints, 10000);
                            console.log('使用简单约束成功获取摄像头');
                            videoPreview.srcObject = currentStream;
                            videoPreview.style.display = 'block';
                            console.log('摄像头已打开（使用简单约束）');
                            return; // 成功获取，直接返回
                        } catch (simpleError) {
                            console.error('使用简单约束也失败:', simpleError);
                            // 尝试最基本的约束
                            const basicConstraints = { video: true };
                            try {
                                currentStream = await createGetUserMediaWithTimeout(basicConstraints, 10000);
                                console.log('使用基本约束成功获取摄像头');
                                videoPreview.srcObject = currentStream;
                                videoPreview.style.display = 'block';
                                console.log('摄像头已打开（使用基本约束）');
                                return;
                            } catch (basicError) {
                                console.error('使用基本约束也失败:', basicError);
                                throw simpleError; // 抛出原始错误
                            }
                        }
                    } else if (errorMessage && errorMessage.includes('Timeout') || errorName === 'TimeoutError') {
                        // 超时错误特殊处理
                        console.warn('摄像头启动超时，尝试重试...');
                        // 尝试使用更简单的约束重试一次
                        try {
                            const retryConstraints = { video: true };
                            currentStream = await createGetUserMediaWithTimeout(retryConstraints, 15000); // 增加超时时间到15秒
                            console.log('重试成功获取摄像头');
                            videoPreview.srcObject = currentStream;
                            videoPreview.style.display = 'block';
                            console.log('摄像头已打开（重试成功）');
                            return;
                        } catch (retryError) {
                            throw new Error(`摄像头启动超时，请检查：\n1. 摄像头是否正常工作\n2. 是否有其他应用占用摄像头\n3. 系统权限是否已授予\n4. 尝试重启应用`);
                        }
                    } else {
                        throw new Error(`获取摄像头失败: ${errorMessage || errorName}`);
                    }
                }
            } catch (error) {
                console.error('打开摄像头失败:', error);
                console.error('错误堆栈:', error.stack);
                console.error('错误详情:', {
                    name: error.name,
                    message: error.message,
                    code: error.code,
                    constraint: error.constraint
                });
                
                // 清理资源
                if (currentStream) {
                    currentStream.getTracks().forEach(track => {
                        track.stop();
                    });
                    currentStream = null;
                }
                
                // 显示详细错误信息
                let errorMessage = `无法打开摄像头: ${error.message || '未知错误'}`;
                errorMessage += `\n\n可能的原因：`;
                errorMessage += `\n1. 摄像头权限被拒绝（请在系统设置中允许应用访问摄像头）`;
                errorMessage += `\n2. 摄像头被其他应用占用`;
                errorMessage += `\n3. 设备没有摄像头`;
                errorMessage += `\n4. 浏览器不支持摄像头功能`;
                errorMessage += `\n5. 鸿蒙平台兼容性问题`;
                errorMessage += `\n\n错误代码: ${error.name || 'N/A'}`;
                
                cameraError.style.display = 'block';
                cameraError.textContent = errorMessage;
                videoPreview.style.display = 'none';
            }
        }
        
        // 拍照
        function takePhoto() {
            console.log('拍照');
            const videoPreview = document.getElementById('video-preview');
            const canvas = document.getElementById('photo-canvas');
            const photoImage = document.getElementById('photo-image');
            const photoPreview = document.getElementById('photo-preview');
            
            if (!currentStream || !videoPreview.srcObject) {
                alert('请先打开摄像头');
                return;
            }
            
            // 检查视频是否已加载
            if (videoPreview.readyState !== videoPreview.HAVE_ENOUGH_DATA && 
                videoPreview.readyState !== videoPreview.HAVE_CURRENT_DATA) {
                alert('视频流尚未准备好，请稍候再试');
                return;
            }
            
            // 检查视频尺寸
            if (videoPreview.videoWidth === 0 || videoPreview.videoHeight === 0) {
                alert('视频流无效，请重新打开摄像头');
                return;
            }
            
            try {
                // 设置canvas尺寸与视频相同
                const videoWidth = videoPreview.videoWidth;
                const videoHeight = videoPreview.videoHeight;
                
                canvas.width = videoWidth;
                canvas.height = videoHeight;
                
                console.log('视频尺寸:', videoWidth, 'x', videoHeight);
                
                // 将视频帧绘制到canvas
                const ctx = canvas.getContext('2d');
                
                // 确保视频已加载
                if (videoPreview.readyState >= videoPreview.HAVE_CURRENT_DATA) {
                    ctx.drawImage(videoPreview, 0, 0, canvas.width, canvas.height);
                    console.log('视频帧已绘制到canvas');
                } else {
                    throw new Error('视频流未准备好');
                }
                
                // 将canvas转换为图片数据
                // 尝试使用高质量PNG，如果失败则使用JPEG
                let imageData = null;
                try {
                    imageData = canvas.toDataURL('image/png', 1.0);
                    console.log('已生成PNG格式照片');
                } catch (pngError) {
                    console.warn('PNG格式失败，尝试JPEG:', pngError);
                    try {
                        imageData = canvas.toDataURL('image/jpeg', 0.95);
                        console.log('已生成JPEG格式照片');
                    } catch (jpegError) {
                        console.error('所有格式都失败:', jpegError);
                        throw new Error('无法生成图片数据');
                    }
                }
                
                if (!imageData) {
                    throw new Error('图片数据生成失败');
                }
                
                currentPhotoData = imageData;
                
                // 显示照片预览
                photoImage.src = currentPhotoData;
                photoPreview.style.display = 'block';
                
                // 计算图片大小
                const imageSizeKB = (imageData.length * 0.75 / 1024).toFixed(2); // Base64编码后大小约为原大小的1.33倍
                console.log('照片已拍摄，尺寸:', canvas.width, 'x', canvas.height, '，大小:', imageSizeKB, 'KB');
                
            } catch (error) {
                console.error('拍照失败:', error);
                console.error('错误堆栈:', error.stack);
                alert('拍照失败: ' + error.message);
            }
        }
        
        // 保存照片
        async function savePhoto() {
            if (!currentPhotoData) {
                alert('没有可保存的照片');
                return;
            }
            
            try {
                // 生成文件名（带时间戳）
                const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
                const fileName = `photo-${timestamp}.png`;
                
                if (window.electronAPI && window.electronAPI.saveImage) {
                    // 使用Electron的saveImage功能保存
                    const result = await window.electronAPI.saveImage(currentPhotoData, fileName);
                    
                    if (!result.canceled && result.filePath) {
                        if (result.saved) {
                            alert(`照片已保存到:\n${result.filePath}`);
                        } else {
                            alert(`请将照片保存到:\n${result.filePath}`);
                        }
                    }
                } else {
                    // 降级方案：使用浏览器下载
                    const link = document.createElement('a');
                    link.download = fileName;
                    link.href = currentPhotoData;
                    link.click();
                    alert('照片已下载');
                }
            } catch (error) {
                console.error('保存照片失败:', error);
                alert('保存照片失败: ' + error.message);
            }
        }
        
        // 重新拍摄
        function retakePhoto() {
            const photoPreview = document.getElementById('photo-preview');
            photoPreview.style.display = 'none';
            currentPhotoData = null;
            console.log('准备重新拍摄');
        }
        
        // 关闭摄像头
        function closeCamera() {
            console.log('关闭摄像头');
            
            if (currentStream) {
                currentStream.getTracks().forEach(track => track.stop());
                currentStream = null;
            }
            
            const videoPreview = document.getElementById('video-preview');
            const cameraContainer = document.getElementById('camera-container');
            const photoPreview = document.getElementById('photo-preview');
            
            videoPreview.srcObject = null;
            videoPreview.style.display = 'none';
            photoPreview.style.display = 'none';
            cameraContainer.style.display = 'none';
            currentPhotoData = null;
            
            console.log('摄像头已关闭');
        }
        
        // 录音相关变量
        let mediaRecorder = null;
        let audioStream = null;
        let recordedChunks = [];
        let recordingStartTime = null;
        let recordingTimer = null;
        let currentAudioBlob = null;
        
        // 开始录音
        async function startRecording() {
            console.log('开始录音');
            const recordingContainer = document.getElementById('recording-container');
            const recordingError = document.getElementById('recording-error');
            const startBtn = document.getElementById('start-recording-btn');
            const stopBtn = document.getElementById('stop-recording-btn');
            const playBtn = document.getElementById('play-recording-btn');
            const pauseBtn = document.getElementById('pause-recording-btn');
            const saveBtn = document.getElementById('save-recording-btn');
            const recordingIndicator = document.getElementById('recording-indicator');
            const recordingTime = document.getElementById('recording-time');
            const audioPlayer = document.getElementById('audio-player');
            const recordingInfo = document.getElementById('recording-info');
            
            recordingError.style.display = 'none';
            recordingContainer.style.display = 'block';
            
            try {
                // 检查浏览器是否支持MediaRecorder
                if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
                    throw new Error('您的浏览器不支持麦克风访问功能');
                }
                
                // 检查是否支持MediaRecorder
                if (!window.MediaRecorder) {
                    throw new Error('您的浏览器不支持录音功能');
                }
                
                console.log('开始请求麦克风权限...');
                
                // 请求麦克风权限并获取音频流
                // 鸿蒙平台可能需要更简单的约束配置
                const constraints = {
                    audio: {
                        echoCancellation: true,
                        noiseSuppression: true,
                        autoGainControl: true
                    }
                };
                
                try {
                    audioStream = await navigator.mediaDevices.getUserMedia(constraints);
                    console.log('麦克风已获取，音频轨道数:', audioStream.getAudioTracks().length);
                    
                    // 检查音频轨道
                    const audioTracks = audioStream.getAudioTracks();
                    if (audioTracks.length === 0) {
                        throw new Error('未获取到音频轨道');
                    }
                    
                    console.log('音频轨道信息:', {
                        label: audioTracks[0].label,
                        enabled: audioTracks[0].enabled,
                        muted: audioTracks[0].muted,
                        readyState: audioTracks[0].readyState,
                        settings: audioTracks[0].getSettings()
                    });
                } catch (getUserMediaError) {
                    console.error('getUserMedia 错误详情:', getUserMediaError);
                    const errorName = getUserMediaError.name;
                    const errorMessage = getUserMediaError.message;
                    
                    if (errorName === 'NotAllowedError' || errorName === 'PermissionDeniedError') {
                        throw new Error('麦克风权限被拒绝，请在系统设置中允许应用访问麦克风');
                    } else if (errorName === 'NotFoundError' || errorName === 'DevicesNotFoundError') {
                        throw new Error('未找到可用的麦克风设备');
                    } else if (errorName === 'NotReadableError' || errorName === 'TrackStartError') {
                        throw new Error('麦克风被其他应用占用，请关闭其他使用麦克风的应用后重试');
                    } else if (errorName === 'OverconstrainedError' || errorName === 'ConstraintNotSatisfiedError') {
                        // 尝试使用更简单的约束
                        console.log('约束不满足，尝试使用简单约束...');
                        const simpleConstraints = { audio: true };
                        audioStream = await navigator.mediaDevices.getUserMedia(simpleConstraints);
                        console.log('使用简单约束成功获取麦克风');
                    } else {
                        throw new Error(`获取麦克风失败: ${errorMessage || errorName}`);
                    }
                }
                
                // 检查浏览器支持的MIME类型（鸿蒙平台可能需要特殊处理）
                const supportedTypes = [
                    'audio/webm',
                    'audio/webm;codecs=opus',
                    'audio/ogg;codecs=opus',
                    'audio/ogg',
                    'audio/mp4',
                    'audio/mpeg',
                    'audio/wav',
                    'audio/x-m4a'
                ];
                
                let mimeType = '';
                for (const type of supportedTypes) {
                    if (MediaRecorder.isTypeSupported(type)) {
                        mimeType = type;
                        console.log('找到支持的格式:', type);
                        break;
                    }
                }
                
                if (!mimeType) {
                    console.warn('未找到明确支持的格式，使用浏览器默认格式');
                    mimeType = ''; // 使用浏览器默认格式
                }
                
                console.log('使用的录音格式:', mimeType || '浏览器默认格式');
                
                // 创建MediaRecorder实例
                const options = mimeType ? { mimeType: mimeType } : {};
                
                try {
                    mediaRecorder = new MediaRecorder(audioStream, options);
                    console.log('MediaRecorder 创建成功，状态:', mediaRecorder.state);
                    console.log('MediaRecorder MIME类型:', mediaRecorder.mimeType);
                } catch (recorderError) {
                    console.error('创建 MediaRecorder 失败:', recorderError);
                    // 尝试不使用选项创建
                    try {
                        console.log('尝试不使用选项创建 MediaRecorder...');
                        mediaRecorder = new MediaRecorder(audioStream);
                        console.log('使用默认选项创建成功');
                    } catch (fallbackError) {
                        throw new Error(`创建录音器失败: ${fallbackError.message || '未知错误'}`);
                    }
                }
                
                // 重置录音数据
                recordedChunks = [];
                
                // 监听数据可用事件
                mediaRecorder.ondataavailable = (event) => {
                    if (event.data.size > 0) {
                        recordedChunks.push(event.data);
                        console.log('录音数据块已接收，大小:', event.data.size, '字节');
                    }
                };
                
                // 监听录音停止事件
                mediaRecorder.onstop = () => {
                    console.log('录音已停止');
                    const blob = new Blob(recordedChunks, { type: mediaRecorder.mimeType });
                    currentAudioBlob = blob;
                    
                    // 创建音频URL
                    const audioUrl = URL.createObjectURL(blob);
                    audioPlayer.src = audioUrl;
                    audioPlayer.style.display = 'block';
                    
                    // 显示录音信息
                    const duration = Math.round(blob.size / 1000); // 估算时长（秒）
                    const sizeKB = (blob.size / 1024).toFixed(2);
                    document.getElementById('recording-duration').textContent = `${duration} 秒`;
                    document.getElementById('recording-size').textContent = `${sizeKB} KB`;
                    recordingInfo.style.display = 'block';
                    
                    // 更新按钮状态
                    stopBtn.style.display = 'none';
                    startBtn.style.display = 'inline-block';
                    playBtn.style.display = 'inline-block';
                    saveBtn.style.display = 'inline-block';
                    recordingIndicator.style.display = 'none';
                    
                    // 停止计时器
                    if (recordingTimer) {
                        clearInterval(recordingTimer);
                        recordingTimer = null;
                    }
                    recordingTime.textContent = '00:00';
                    
                    console.log('录音完成，总大小:', blob.size, '字节，格式:', mediaRecorder.mimeType);
                };
                
                // 监听录音错误事件
                mediaRecorder.onerror = (event) => {
                    console.error('录音错误:', event);
                    const errorMsg = event.error?.message || event.error?.name || '未知错误';
                    console.error('错误详情:', {
                        error: event.error,
                        errorName: event.error?.name,
                        errorMessage: event.error?.message
                    });
                    recordingError.style.display = 'block';
                    recordingError.textContent = `录音错误: ${errorMsg}`;
                    stopRecording();
                };
                
                // 监听录音开始事件
                mediaRecorder.onstart = () => {
                    console.log('录音已开始，状态:', mediaRecorder.state);
                };
                
                // 监听录音暂停事件
                mediaRecorder.onpause = () => {
                    console.log('录音已暂停');
                };
                
                // 监听录音恢复事件
                mediaRecorder.onresume = () => {
                    console.log('录音已恢复');
                };
                
                // 开始录音
                try {
                    // 鸿蒙平台可能需要不同的时间间隔，尝试使用更小的值
                    const timeslice = 1000; // 每1秒收集一次数据
                    mediaRecorder.start(timeslice);
                    recordingStartTime = Date.now();
                    console.log('已调用 mediaRecorder.start()，当前状态:', mediaRecorder.state);
                } catch (startError) {
                    console.error('启动录音失败:', startError);
                    throw new Error(`启动录音失败: ${startError.message || '未知错误'}`);
                }
                
                // 更新UI
                startBtn.style.display = 'none';
                stopBtn.style.display = 'inline-block';
                playBtn.style.display = 'none';
                pauseBtn.style.display = 'none';
                saveBtn.style.display = 'none';
                recordingIndicator.style.display = 'block';
                audioPlayer.style.display = 'none';
                recordingInfo.style.display = 'none';
                
                // 开始计时
                recordingTimer = setInterval(() => {
                    const elapsed = Math.floor((Date.now() - recordingStartTime) / 1000);
                    const minutes = Math.floor(elapsed / 60);
                    const seconds = elapsed % 60;
                    recordingTime.textContent = `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
                }, 1000);
                
                console.log('录音已开始');
            } catch (error) {
                console.error('开始录音失败:', error);
                console.error('错误堆栈:', error.stack);
                console.error('错误详情:', {
                    name: error.name,
                    message: error.message,
                    code: error.code,
                    constraint: error.constraint
                });
                
                // 清理资源
                if (audioStream) {
                    audioStream.getTracks().forEach(track => {
                        track.stop();
                    });
                    audioStream = null;
                }
                
                // 显示详细错误信息
                let errorMessage = `无法开始录音: ${error.message || '未知错误'}`;
                errorMessage += `\n\n可能的原因：`;
                errorMessage += `\n1. 麦克风权限被拒绝（请在系统设置中允许应用访问麦克风）`;
                errorMessage += `\n2. 麦克风被其他应用占用`;
                errorMessage += `\n3. 设备没有麦克风`;
                errorMessage += `\n4. 浏览器不支持录音功能`;
                errorMessage += `\n5. 鸿蒙平台兼容性问题`;
                errorMessage += `\n\n错误代码: ${error.name || 'N/A'}`;
                
                recordingError.style.display = 'block';
                recordingError.textContent = errorMessage;
                
                // 重置UI
                const startBtn = document.getElementById('start-recording-btn');
                const stopBtn = document.getElementById('stop-recording-btn');
                if (startBtn) startBtn.style.display = 'inline-block';
                if (stopBtn) stopBtn.style.display = 'none';
            }
        }
        
        // 停止录音
        function stopRecording() {
            console.log('停止录音');
            
            if (mediaRecorder && mediaRecorder.state !== 'inactive') {
                mediaRecorder.stop();
            }
            
            // 停止音频流
            if (audioStream) {
                audioStream.getTracks().forEach(track => {
                    track.stop();
                });
                audioStream = null;
            }
            
            // 停止计时器
            if (recordingTimer) {
                clearInterval(recordingTimer);
                recordingTimer = null;
            }
        }
        
        // 播放录音
        function playRecording() {
            console.log('播放录音');
            const audioPlayer = document.getElementById('audio-player');
            const playBtn = document.getElementById('play-recording-btn');
            const pauseBtn = document.getElementById('pause-recording-btn');
            
            if (!currentAudioBlob) {
                alert('没有可播放的录音');
                return;
            }
            
            if (audioPlayer.paused) {
                audioPlayer.play();
                playBtn.style.display = 'none';
                pauseBtn.style.display = 'inline-block';
                console.log('开始播放录音');
                } else {
                audioPlayer.pause();
                playBtn.style.display = 'inline-block';
                pauseBtn.style.display = 'none';
                console.log('暂停播放录音');
            }
        }
        
        // 暂停播放
        function pauseRecording() {
            console.log('暂停播放');
            const audioPlayer = document.getElementById('audio-player');
            const playBtn = document.getElementById('play-recording-btn');
            const pauseBtn = document.getElementById('pause-recording-btn');
            
            audioPlayer.pause();
            playBtn.style.display = 'inline-block';
            pauseBtn.style.display = 'none';
        }
        
        // 保存录音
        async function saveRecording() {
            if (!currentAudioBlob) {
                alert('没有可保存的录音');
                return;
            }
            
            try {
                // 生成文件名（带时间戳）
                const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
                const fileName = `recording-${timestamp}.webm`;
                
                console.log('开始保存录音，文件名:', fileName);
                
                // 将Blob转换为Base64
                const reader = new FileReader();
                reader.onloadend = async () => {
                    const base64Data = reader.result.split(',')[1]; // 移除data:audio/webm;base64,前缀
                    
                    if (window.electronAPI && window.electronAPI.saveAudio) {
                        const result = await window.electronAPI.saveAudio(base64Data, fileName, currentAudioBlob.type);
                        
                        if (!result.canceled && result.filePath) {
                            if (result.saved) {
                                console.log('录音已保存到:', result.filePath);
                                alert(`录音已保存到:\n${result.filePath}`);
                            } else {
                                console.log('保存失败，文件路径:', result.filePath);
                                alert(`保存失败，请检查文件路径:\n${result.filePath}`);
                            }
                        } else {
                            console.log('用户取消了保存');
                        }
                    } else {
                        // 降级方案：使用浏览器下载
                        console.log('使用浏览器下载作为降级方案');
                        const link = document.createElement('a');
                        link.download = fileName;
                        link.href = URL.createObjectURL(currentAudioBlob);
                        document.body.appendChild(link);
                        link.click();
                        document.body.removeChild(link);
                        alert('录音已下载');
                    }
                };
                reader.onerror = (error) => {
                    console.error('读取录音文件失败:', error);
                    alert('读取录音文件失败: ' + error.message);
                };
                reader.readAsDataURL(currentAudioBlob);
            } catch (error) {
                console.error('保存录音失败:', error);
                alert('保存录音失败: ' + error.message);
            }
        }
        
        // 获取当前地理位置
        function getCurrentLocation() {
            console.log('点击获取地理位置按钮');
            const locationInfoDiv = document.getElementById('location-info');
            const locationDetailsDiv = document.getElementById('location-details');
            const locationErrorDiv = document.getElementById('location-error');
            
            // 显示容器
            locationInfoDiv.style.display = 'block';
            locationErrorDiv.style.display = 'none';
            locationDetailsDiv.innerHTML = '<p style="color: #ffd43b;">正在获取地理位置...</p>';
            
            // 检查浏览器是否支持地理位置
            if (!navigator.geolocation) {
                const errorMsg = '您的浏览器不支持地理位置功能';
                console.error(errorMsg);
                locationErrorDiv.style.display = 'block';
                locationErrorDiv.textContent = errorMsg;
                locationDetailsDiv.innerHTML = '';
                return;
            }
            
            // 地理位置选项
            const options = {
                enableHighAccuracy: true,  // 启用高精度
                timeout: 15000,            // 超时时间15秒
                maximumAge: 0              // 不使用缓存的位置
            };
            
            // 获取当前位置
            navigator.geolocation.getCurrentPosition(
                // 成功回调
                (position) => {
                    console.log('获取地理位置成功:', position);
                    
                    const coords = position.coords;
                    const timestamp = new Date(position.timestamp);
                    
                    // 构建显示内容
                    let html = '';
                    
                    // 主要信息卡片
                    html += `<div style="margin-bottom: 20px; padding: 20px; background: rgba(81, 207, 102, 0.2); border-radius: 10px; border-left: 4px solid #51cf66;">
                        <div style="font-size: 48px; text-align: center; margin-bottom: 15px;">
                            📍
                        </div>
                        <div style="text-align: center; font-size: 24px; font-weight: bold; color: #51cf66; margin-bottom: 10px;">
                            位置获取成功
                        </div>
                    </div>`;
                    
                    // 经纬度信息
                    html += `<div style="margin-bottom: 15px; padding: 15px; background: rgba(255, 255, 255, 0.05); border-radius: 8px;">
                        <div style="margin-bottom: 10px;">
                            <strong style="color: #ffd43b;">纬度 (Latitude):</strong>
                            <div style="margin-top: 5px; font-family: monospace; font-size: 18px; color: #51cf66;">
                                ${coords.latitude.toFixed(6)}°
                            </div>
                        </div>
                        <div>
                            <strong style="color: #ffd43b;">经度 (Longitude):</strong>
                            <div style="margin-top: 5px; font-family: monospace; font-size: 18px; color: #51cf66;">
                                ${coords.longitude.toFixed(6)}°
                            </div>
                        </div>
                    </div>`;
                    
                    // 精度信息
                    html += `<div style="margin-bottom: 15px; padding: 15px; background: rgba(255, 255, 255, 0.05); border-radius: 8px;">
                        <div style="margin-bottom: 8px;">
                            <strong style="color: #ffd43b;">精度 (Accuracy):</strong>
                            <span style="margin-left: 10px; color: #51cf66;">±${Math.round(coords.accuracy)} 米</span>
                        </div>`;
                    
                    if (coords.altitude !== null && coords.altitude !== undefined) {
                        html += `<div style="margin-bottom: 8px;">
                            <strong style="color: #ffd43b;">海拔 (Altitude):</strong>
                            <span style="margin-left: 10px; color: #51cf66;">${Math.round(coords.altitude)} 米</span>
                        </div>`;
                    }
                    
                    if (coords.altitudeAccuracy !== null && coords.altitudeAccuracy !== undefined) {
                        html += `<div style="margin-bottom: 8px;">
                            <strong style="color: #ffd43b;">海拔精度:</strong>
                            <span style="margin-left: 10px; color: #51cf66;">±${Math.round(coords.altitudeAccuracy)} 米</span>
                        </div>`;
                    }
                    
                    if (coords.heading !== null && coords.heading !== undefined) {
                        html += `<div style="margin-bottom: 8px;">
                            <strong style="color: #ffd43b;">方向 (Heading):</strong>
                            <span style="margin-left: 10px; color: #51cf66;">${Math.round(coords.heading)}°</span>
                        </div>`;
                    }
                    
                    if (coords.speed !== null && coords.speed !== undefined) {
                        html += `<div>
                            <strong style="color: #ffd43b;">速度 (Speed):</strong>
                            <span style="margin-left: 10px; color: #51cf66;">${(coords.speed * 3.6).toFixed(2)} 公里/小时</span>
                        </div>`;
                    }
                    
                    html += `</div>`;
                    
                    // 时间戳
                    html += `<div style="margin-bottom: 15px; padding: 10px; background: rgba(255, 255, 255, 0.05); border-radius: 5px;">
                        <strong style="color: #ffd43b;">获取时间:</strong>
                        <div style="margin-top: 5px; color: rgba(255, 255, 255, 0.8);">
                            ${timestamp.toLocaleString('zh-CN')}
                        </div>
                    </div>`;
                    
                    // 地图链接
                    html += `<div style="margin-top: 20px; padding: 15px; background: rgba(255, 255, 255, 0.05); border-radius: 8px;">
                        <strong style="color: #ffd43b; display: block; margin-bottom: 10px;">在地图上查看:</strong>
                        <div style="display: flex; gap: 10px; flex-wrap: wrap;">
                            <a href="https://www.openstreetmap.org/?mlat=${coords.latitude}&mlon=${coords.longitude}&zoom=15" 
                               target="_blank" 
                               style="display: inline-block; padding: 10px 20px; background: #51cf66; color: white; text-decoration: none; border-radius: 5px; margin-right: 10px;">
                                🗺️ OpenStreetMap
                            </a>
                            <a href="https://www.google.com/maps?q=${coords.latitude},${coords.longitude}" 
                               target="_blank" 
                               style="display: inline-block; padding: 10px 20px; background: #4285f4; color: white; text-decoration: none; border-radius: 5px; margin-right: 10px;">
                                🗺️ Google Maps
                            </a>
                            <a href="https://api.map.baidu.com/marker?location=${coords.latitude},${coords.longitude}&title=当前位置&content=纬度:${coords.latitude},经度:${coords.longitude}" 
                               target="_blank" 
                               style="display: inline-block; padding: 10px 20px; background: #3385ff; color: white; text-decoration: none; border-radius: 5px;">
                                🗺️ 百度地图
                            </a>
                        </div>
                    </div>`;
                    
                    // 复制坐标按钮
                    html += `<div style="margin-top: 15px;">
                        <button onclick="copyLocationToClipboard(${coords.latitude}, ${coords.longitude})" 
                                style="padding: 10px 20px; background: #ffd43b; color: #000; border: none; border-radius: 5px; cursor: pointer; font-weight: bold;">
                            📋 复制坐标
                        </button>
                    </div>`;
                    
                    locationDetailsDiv.innerHTML = html;
                },
                // 错误回调
                (error) => {
                    console.error('获取地理位置失败:', error);
                    
                    let errorMessage = '';
                    let errorDetails = '';
                    
                    switch (error.code) {
                        case error.PERMISSION_DENIED:
                            errorMessage = '地理位置权限被拒绝';
                            errorDetails = '请在系统设置中允许应用访问您的位置信息，然后重试。';
                            break;
                        case error.POSITION_UNAVAILABLE:
                            errorMessage = '无法获取位置信息';
                            errorDetails = '设备无法确定当前位置，请检查GPS是否开启，或尝试在室外使用。';
                            break;
                        case error.TIMEOUT:
                            errorMessage = '获取位置超时';
                            errorDetails = '获取位置信息超时，请检查网络连接或GPS信号，然后重试。';
                            break;
                        default:
                            errorMessage = '获取地理位置失败';
                            errorDetails = error.message || '未知错误';
                            break;
                    }
                    
                    locationErrorDiv.style.display = 'block';
                    locationErrorDiv.innerHTML = `
                        <div style="color: #ff6b6b; font-weight: bold; margin-bottom: 10px;">
                            ❌ ${errorMessage}
                        </div>
                        <div style="color: rgba(255, 255, 255, 0.8);">
                            ${errorDetails}
                        </div>
                        <div style="margin-top: 10px; color: rgba(255, 255, 255, 0.6); font-size: 14px;">
                            错误代码: ${error.code} (${error.code === 1 ? 'PERMISSION_DENIED' : error.code === 2 ? 'POSITION_UNAVAILABLE' : error.code === 3 ? 'TIMEOUT' : 'UNKNOWN_ERROR'})
                    </div>
                `;
                    locationDetailsDiv.innerHTML = '';
                },
                // 选项
                options
            );
        }
        
        // 复制坐标到剪贴板
        function copyLocationToClipboard(latitude, longitude) {
            const text = `${latitude}, ${longitude}`;
            
            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(text).then(() => {
                    alert('坐标已复制到剪贴板: ' + text);
                }).catch(err => {
                    console.error('复制失败:', err);
                    // 降级方案
                    fallbackCopyToClipboard(text);
                });
            } else {
                // 降级方案
                fallbackCopyToClipboard(text);
            }
        }
        
        // 降级复制方案
        function fallbackCopyToClipboard(text) {
            const textArea = document.createElement('textarea');
            textArea.value = text;
            textArea.style.position = 'fixed';
            textArea.style.left = '-999999px';
            document.body.appendChild(textArea);
            textArea.select();
            try {
                document.execCommand('copy');
                alert('坐标已复制到剪贴板: ' + text);
            } catch (err) {
                console.error('复制失败:', err);
                alert('无法复制到剪贴板，请手动复制: ' + text);
            }
            document.body.removeChild(textArea);
        }
        
        // 关闭录音
        function closeRecording() {
            console.log('关闭录音');
            
            // 停止录音
            if (mediaRecorder && mediaRecorder.state !== 'inactive') {
                mediaRecorder.stop();
            }
            
            // 停止音频流
            if (audioStream) {
                audioStream.getTracks().forEach(track => {
                    track.stop();
                });
                audioStream = null;
            }
            
            // 停止播放
            const audioPlayer = document.getElementById('audio-player');
            if (audioPlayer) {
                audioPlayer.pause();
                audioPlayer.src = '';
            }
            
            // 停止计时器
            if (recordingTimer) {
                clearInterval(recordingTimer);
                recordingTimer = null;
            }
            
            // 清理资源
            if (currentAudioBlob) {
                const audioUrl = audioPlayer?.src;
                if (audioUrl && audioUrl.startsWith('blob:')) {
                    URL.revokeObjectURL(audioUrl);
                }
                currentAudioBlob = null;
            }
            
            const recordingContainer = document.getElementById('recording-container');
            recordingContainer.style.display = 'none';
            
            // 重置UI
            const startBtn = document.getElementById('start-recording-btn');
            const stopBtn = document.getElementById('stop-recording-btn');
            const playBtn = document.getElementById('play-recording-btn');
            const pauseBtn = document.getElementById('pause-recording-btn');
            const saveBtn = document.getElementById('save-recording-btn');
            const recordingIndicator = document.getElementById('recording-indicator');
            const recordingTime = document.getElementById('recording-time');
            const recordingInfo = document.getElementById('recording-info');
            
            startBtn.style.display = 'inline-block';
            stopBtn.style.display = 'none';
            playBtn.style.display = 'none';
            pauseBtn.style.display = 'none';
            saveBtn.style.display = 'none';
            recordingIndicator.style.display = 'none';
            recordingTime.textContent = '00:00';
            recordingInfo.style.display = 'none';
            
            console.log('录音功能已关闭');
        }
        
        // 截图相关变量
        let currentScreenshotData = null;
        let currentScreenshotInfo = null;
        
        // 打开截图功能
        function captureScreenshot() {
            const screenshotContainer = document.getElementById('screenshot-container');
            screenshotContainer.style.display = 'block';
        }
        
        // 截取当前窗口
        async function captureWindow() {
            console.log('截取当前窗口');
            const screenshotPreview = document.getElementById('screenshot-preview');
            const screenshotImage = document.getElementById('screenshot-image');
            const screenshotInfo = document.getElementById('screenshot-info');
            const screenshotError = document.getElementById('screenshot-error');
            
            screenshotError.style.display = 'none';
            
            try {
                if (window.electronAPI && window.electronAPI.captureWindow) {
                    const result = await window.electronAPI.captureWindow();
                    
                    if (result.success) {
                        currentScreenshotData = result.dataUrl;
                        currentScreenshotInfo = {
                            type: '窗口',
                            width: result.width,
                            height: result.height
                        };
                        
                        screenshotImage.src = result.dataUrl;
                        screenshotInfo.textContent = `类型: 窗口截图 | 尺寸: ${result.width} x ${result.height} 像素`;
                        screenshotPreview.style.display = 'block';
                        console.log('窗口截图已捕获');
                    } else {
                        throw new Error(result.error || '截取窗口失败');
                    }
                } else {
                    throw new Error('截图功能不可用');
                }
            } catch (error) {
                console.error('截取窗口失败:', error);
                screenshotError.style.display = 'block';
                screenshotError.textContent = `截取窗口失败: ${error.message}`;
                screenshotPreview.style.display = 'none';
            }
        }
        
        // 打开浏览器
        async function openBrowser() {
            console.log('点击打开浏览器按钮');
            
            try {
                // 显示URL输入对话框
                const browserDialog = document.getElementById('browser-dialog');
                const browserUrlInput = document.getElementById('browser-url-input');
                const browserDialogCancel = document.getElementById('browser-dialog-cancel');
                const browserDialogOk = document.getElementById('browser-dialog-ok');
                
                if (browserDialog && browserUrlInput) {
                    // 显示对话框
                    browserDialog.style.display = 'flex';
                    browserUrlInput.value = 'https://www.openharmony.cn';
                    browserUrlInput.focus();
                    browserUrlInput.select();
                    
                    // 等待用户输入
                    return new Promise((resolve) => {
                        const handleOk = async () => {
                            const url = browserUrlInput.value.trim() || 'https://www.openharmony.cn';
                            browserDialog.style.display = 'none';
                            
                            // 清理事件监听
                            browserDialogOk.removeEventListener('click', handleOk);
                            browserDialogCancel.removeEventListener('click', handleCancel);
                            browserUrlInput.removeEventListener('keypress', handleKeyPress);
                            
                            try {
                                if (window.electronAPI && window.electronAPI.createBrowserWindow) {
                                    const result = await window.electronAPI.createBrowserWindow(url);
                                    
                                    if (result.success) {
                                        console.log('浏览器窗口创建成功:', result.windowId);
                                    } else {
                                        console.error('打开浏览器失败:', result.error);
                                        // 使用页面内提示而不是alert
                                        showMessage('打开浏览器失败: ' + (result.error || '未知错误'), 'error');
                                    }
                                } else {
                                    showMessage('浏览器功能不可用', 'error');
                                }
                            } catch (error) {
                                console.error('打开浏览器失败:', error);
                                showMessage('打开浏览器失败: ' + error.message, 'error');
                            }
                            
                            resolve();
                        };
                        
                        const handleCancel = () => {
                            browserDialog.style.display = 'none';
                            
                            // 清理事件监听
                            browserDialogOk.removeEventListener('click', handleOk);
                            browserDialogCancel.removeEventListener('click', handleCancel);
                            browserUrlInput.removeEventListener('keypress', handleKeyPress);
                            
                            resolve();
                        };
                        
                        const handleKeyPress = (event) => {
                            if (event.key === 'Enter') {
                                handleOk();
                            } else if (event.key === 'Escape') {
                                handleCancel();
                            }
                        };
                        
                        browserDialogOk.addEventListener('click', handleOk);
                        browserDialogCancel.addEventListener('click', handleCancel);
                        browserUrlInput.addEventListener('keypress', handleKeyPress);
                    });
                } else {
                    // 如果对话框元素不存在，直接使用默认URL
                    const defaultUrl = 'https://www.openharmony.cn';
                    
                    if (window.electronAPI && window.electronAPI.createBrowserWindow) {
                        const result = await window.electronAPI.createBrowserWindow(defaultUrl);
                        
                        if (result.success) {
                            console.log('浏览器窗口创建成功:', result.windowId);
                        } else {
                            console.error('打开浏览器失败:', result.error);
                            showMessage('打开浏览器失败: ' + (result.error || '未知错误'), 'error');
                        }
                    } else {
                        showMessage('浏览器功能不可用', 'error');
                    }
                }
            } catch (error) {
                console.error('打开浏览器失败:', error);
                showMessage('打开浏览器失败: ' + error.message, 'error');
            }
        }
        
        // 显示消息提示（替代alert）
        function showMessage(message, type = 'info') {
            // 创建或获取消息容器
            let messageContainer = document.getElementById('message-container');
            if (!messageContainer) {
                messageContainer = document.createElement('div');
                messageContainer.id = 'message-container';
                messageContainer.style.cssText = 'position: fixed; top: 20px; right: 20px; z-index: 10000; max-width: 400px;';
                document.body.appendChild(messageContainer);
            }
            
            // 创建消息元素
            const messageDiv = document.createElement('div');
            const bgColor = type === 'error' ? '#ff6b6b' : type === 'success' ? '#51cf66' : '#ffd43b';
            messageDiv.style.cssText = `
                background: ${bgColor};
                color: white;
                padding: 15px 20px;
                border-radius: 8px;
                margin-bottom: 10px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.3);
                animation: slideIn 0.3s ease-out;
            `;
            messageDiv.textContent = message;
            
            messageContainer.appendChild(messageDiv);
            
            // 3秒后自动移除
            setTimeout(() => {
                messageDiv.style.animation = 'slideOut 0.3s ease-out';
                setTimeout(() => {
                    if (messageDiv.parentNode) {
                        messageDiv.parentNode.removeChild(messageDiv);
                    }
                }, 300);
            }, 3000);
        }
        
        // 截取屏幕
        async function captureScreen() {
            console.log('截取屏幕');
            const screenshotPreview = document.getElementById('screenshot-preview');
            const screenshotImage = document.getElementById('screenshot-image');
            const screenshotInfo = document.getElementById('screenshot-info');
            const screenshotError = document.getElementById('screenshot-error');
            
            screenshotError.style.display = 'none';
            
            try {
                if (window.electronAPI && window.electronAPI.captureScreen) {
                    // 不指定sourceId，使用默认屏幕
                    const result = await window.electronAPI.captureScreen(null);
                    
                    if (result.success) {
                        currentScreenshotData = result.dataUrl;
                        currentScreenshotInfo = {
                            type: '屏幕',
                            width: result.width,
                            height: result.height,
                            sourceName: result.sourceName
                        };
                        
                        screenshotImage.src = result.dataUrl;
                        screenshotInfo.textContent = `类型: 屏幕截图 | 尺寸: ${result.width} x ${result.height} 像素 | 源: ${result.sourceName || '默认屏幕'}`;
                        screenshotPreview.style.display = 'block';
                        console.log('屏幕截图已捕获');
                    } else {
                        throw new Error(result.error || '截取屏幕失败');
                    }
                } else {
                    throw new Error('截图功能不可用');
                }
            } catch (error) {
                console.error('截取屏幕失败:', error);
                screenshotError.style.display = 'block';
                screenshotError.textContent = `截取屏幕失败: ${error.message}`;
                screenshotPreview.style.display = 'none';
            }
        }
        
        // 保存截图
        async function saveScreenshot() {
            if (!currentScreenshotData) {
                alert('没有可保存的截图');
                return;
            }
            
            try {
                // 生成文件名（带时间戳和类型）
                const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
                const type = currentScreenshotInfo?.type || 'screenshot';
                const fileName = `${type}-${timestamp}.png`;
                
                console.log('开始保存截图，文件名:', fileName);
                
                if (window.electronAPI && window.electronAPI.saveImage) {
                    const result = await window.electronAPI.saveImage(currentScreenshotData, fileName);
                    
                    if (!result.canceled && result.filePath) {
                        if (result.saved) {
                            console.log('截图已保存到:', result.filePath);
                            alert(`截图已保存到:\n${result.filePath}`);
                        } else {
                            console.log('保存失败，文件路径:', result.filePath);
                            alert(`保存失败，请检查文件路径:\n${result.filePath}`);
                        }
                    } else {
                        console.log('用户取消了保存');
                    }
                } else {
                    // 降级方案：使用浏览器下载
                    console.log('使用浏览器下载作为降级方案');
                    const link = document.createElement('a');
                    link.download = fileName;
                    link.href = currentScreenshotData;
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                    alert('截图已下载');
                }
            } catch (error) {
                console.error('保存截图失败:', error);
                alert('保存截图失败: ' + error.message);
            }
        }
        
        // 重新截图
        function retakeScreenshot() {
            const screenshotPreview = document.getElementById('screenshot-preview');
            screenshotPreview.style.display = 'none';
            currentScreenshotData = null;
            currentScreenshotInfo = null;
            console.log('准备重新截图');
        }
        
        // 区域选择截图
        async function captureRegion() {
            console.log('启动区域选择截图');
            const screenshotError = document.getElementById('screenshot-error');
            screenshotError.style.display = 'none';
            
            try {
                if (window.electronAPI && window.electronAPI.startRegionSelect) {
                    const result = await window.electronAPI.startRegionSelect();
                    
                    if (result.success) {
                        console.log('区域选择窗口已打开，等待用户选择区域...');
                        // 监听器在页面加载时已设置，这里不需要重复设置
                    } else {
                        throw new Error(result.error || '启动区域选择失败');
                    }
                } else {
                    throw new Error('区域选择功能不可用');
                }
            } catch (error) {
                console.error('启动区域选择失败:', error);
                screenshotError.style.display = 'block';
                screenshotError.textContent = `启动区域选择失败: ${error.message}`;
            }
        }
        
        // 处理区域选择完成
        function handleRegionSelected(result) {
            console.log('区域选择完成，收到结果:', result);
            const screenshotPreview = document.getElementById('screenshot-preview');
            const screenshotImage = document.getElementById('screenshot-image');
            const screenshotInfo = document.getElementById('screenshot-info');
            const screenshotError = document.getElementById('screenshot-error');
            const screenshotContainer = document.getElementById('screenshot-container');
            
            screenshotError.style.display = 'none';
            
            if (result && result.success) {
                // 保存截图数据
                currentScreenshotData = result.dataUrl;
                currentScreenshotInfo = {
                    type: '区域',
                    width: result.width,
                    height: result.height,
                    x: result.x,
                    y: result.y
                };
                
                // 显示预览
                screenshotImage.src = result.dataUrl;
                screenshotImage.onload = () => {
                    console.log('区域截图预览已加载');
                };
                screenshotImage.onerror = () => {
                    console.error('区域截图预览加载失败');
                    screenshotError.style.display = 'block';
                    screenshotError.textContent = '截图预览加载失败';
                };
                
                // 显示截图信息
                screenshotInfo.textContent = `类型: 区域截图 | 尺寸: ${result.width} x ${result.height} 像素 | 位置: (${result.x}, ${result.y})`;
                screenshotPreview.style.display = 'block';
                
                // 显示截图容器（如果隐藏了）
                screenshotContainer.style.display = 'block';
                
                // 滚动到预览区域
                screenshotPreview.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
                
                console.log('区域截图已捕获并显示预览，可以保存了');
            } else {
                const errorMsg = result?.error || '未知错误';
                console.error('区域截图失败:', errorMsg);
                screenshotError.style.display = 'block';
                screenshotError.textContent = `区域截图失败: ${errorMsg}`;
            }
        }
        
        // 关闭截图
        function closeScreenshot() {
            const screenshotContainer = document.getElementById('screenshot-container');
            const screenshotPreview = document.getElementById('screenshot-preview');
            const screenshotError = document.getElementById('screenshot-error');
            
            screenshotContainer.style.display = 'none';
            screenshotPreview.style.display = 'none';
            screenshotError.style.display = 'none';
            currentScreenshotData = null;
            currentScreenshotInfo = null;
            
            // 取消区域选择（如果正在进行）
            if (window.electronAPI && window.electronAPI.cancelRegionSelect) {
                window.electronAPI.cancelRegionSelect();
            }
            
            console.log('截图功能已关闭');
        }
        
        // 页面加载时初始化
        window.addEventListener('DOMContentLoaded', () => {
            // 检查通知权限
            if ('Notification' in window) {
                console.log('浏览器支持通知功能');
                console.log('当前通知权限:', Notification.permission);
            } else {
                console.log('浏览器不支持通知功能');
            }
            
            // 检查摄像头支持
            if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                console.log('浏览器支持摄像头访问功能');
            } else {
                console.log('浏览器不支持摄像头访问功能');
            }
            
            // 检查麦克风支持
            if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                console.log('浏览器支持麦克风访问功能');
            } else {
                console.log('浏览器不支持麦克风访问功能');
            }
            
            // 检查MediaRecorder支持
            if (window.MediaRecorder) {
                console.log('浏览器支持MediaRecorder功能');
            } else {
                console.log('浏览器不支持MediaRecorder功能');
            }
            
            // 检查地理位置支持
            if (navigator.geolocation) {
                console.log('浏览器支持地理位置功能');
            } else {
                console.log('浏览器不支持地理位置功能');
            }
            
            // 设置区域选择完成监听器（只设置一次）
            if (window.electronAPI && window.electronAPI.onRegionSelected) {
                console.log('设置区域选择完成监听器');
                window.electronAPI.onRegionSelected((regionResult) => {
                    console.log('收到区域选择完成事件');
                    handleRegionSelected(regionResult);
                });
            } else {
                console.warn('区域选择API不可用');
            }
            
            // 监听音频播放结束
            const audioPlayer = document.getElementById('audio-player');
            if (audioPlayer) {
                audioPlayer.addEventListener('ended', () => {
                    const playBtn = document.getElementById('play-recording-btn');
                    const pauseBtn = document.getElementById('pause-recording-btn');
                    if (playBtn && pauseBtn) {
                        playBtn.style.display = 'inline-block';
                        pauseBtn.style.display = 'none';
                        console.log('录音播放结束');
                    }
                });
            }
        });
    </script>
</body>
</html>
